<template>
  <NavBar
    :leftArrow="true"
    :title="title"
    @onClickLeft="goBack" />

  <!-- 写入 -->
  <div
    v-if="pageType === 'write'"
    class="page_input">
    <div class="load-box">
      <textarea
        class="load-textarea"
        maxlength="-1"
        :value="strContent"
        placeholder="请输入..."
        @input="onInputStr" />
    </div>
    <div
      class="btn-load"
      @click="onTapLoad">
      批量加载
    </div>
    <div
      class="btn-clear"
      @click="onClear">
      清除
    </div>
    <div
      v-if="lastKey"
      class="btn-clear"
      @click="onLastOperate">
      继续上一次操作
    </div>
  </div>

  <!-- 读取 -->
  <div
    v-if="pageType === 'read'"
    class="page">
    <div class="msg-box">
      <div class="title">提示信息</div>
      <div class="text">{{ msgTitle }}</div>
      <!-- <div class="text">{{ msgContent }}</div> -->
    </div>

    <div
      class="ndef-box"
      @click="onClickNDEFContent">
      <div class="title">读取信息</div>
      <block v-if="nfcInfo.payload">
        <!-- <div class="content">
          <div class="label">类型：</div>
          <div>{{ nfcInfo.type }}</div>
        </div>
        <div class="content">
          <div class="label">类型描述：</div>
          <div>{{ typeText[nfcInfo.type] || "其它" }}</div>
        </div> -->
        <div class="content">
          <div class="label">内容：</div>
          <div>{{ nfcInfo.payload }}</div>
        </div>
      </block>
      <div
        v-else
        class="placeholder">
        暂无内容
      </div>
    </div>
  </div>
</template>

<script>
import {
  byteToString,
  isEmpty,
  formatNullCharacter,
  throttle,
  generateUUID,
} from "../../utils/nfc.js";
import NavBar from "../../components/NavBar/NavBar.vue";

export default {
  name: "NFCTool",
  components: {
    NavBar,
  },
  data() {
    return {
      title: "NFC工具",
      pageType: "",
      NFCAdapter: null,
      nfcInfo: {},
      msgTitle: "",
      typeText: { U: "网址", T: "文本" },
      strContent: "",
      lastKey: "",
    };
  },
  onLoad(options) {
    if (options.type == "read") {
      this.title = "读取NFC标签";
      this.pageType = "read";
    } else if (options.type == "write") {
      this.title = "写入NFC标签";
      this.pageType = "write";
    }
    this.onInit();
  },
  onShow() {
    // 获取剪切板内容
    // if (this.pageType === "write") {
    //   this.getClipboardData();
    // }
  },
  onHide() {
    this.closeNFC();
  },
  onUnload() {
    this.closeNFC();
  },
  methods: {
    goBack() {
      uni.navigateBack({ delta: 1 });
    },
    // 初始化 NFC
    onInit() {
      let platform = "";
      uni.getSystemInfo({
        success: function (res) {
          console.log("操作系统类型：", res.osName);
          platform = res.osName;
        },
      });

      if (platform == "android") {
        this.NFCAdapter = wx.getNFCAdapter();
        this.NFClistener();
      } else {
        if (platform != "devtools") {
          uni.showToast({
            title: "当前设备不支持",
            icon: "error",
            mask: true,
          });
        }
      }

      this.msgTitle = "小程序NFC暂仅支持安卓设备";
    },

    // 开始监听 NFC
    NFClistener() {
      this.NFCAdapter.startDiscovery({
        success: () => {
          this.msgTitle = "请将设备放入识别区NFC";
          this.msgContent = "";
          // 监听 NFC 标签
          this.NFCAdapter.onDiscovered(this.discoverHandler);
        },
        fail: (error) => {
          this.msgTitle = "请重试";
          console.error(error);
        },
      });
    },

    // 监听回调
    discoverHandler(callback) {
      console.log("==================== START ====================");
      console.log("onDiscovered callback=>", callback);
      if (callback.messages) {
        let cordsArray = callback.messages[0].records;
        cordsArray.forEach((item) => {
          const nfcInfo = {
            payload: formatNullCharacter(
              byteToString(new Uint8Array(item.payload))
            ),
            id: byteToString(new Uint8Array(item.id)),
            type: byteToString(new Uint8Array(item.type)),
          };
          this.nfcInfo = nfcInfo;
        });
      } else {
        this.nfcInfo = {};
      }
      console.log("nfcInfo", this.nfcInfo);

      if (callback.techs.length != 0) {
        let msgContent = "可支持标签：";
        callback.techs.forEach((res, index) => {
          if (index != 0) {
            msgContent += "、";
          }
          msgContent += res;
        });
        this.msgTitle = "识别成功！";
        this.msgContent = msgContent;
      } else {
        this.msgTitle = "无效设备";
      }
      console.log("===================== END =====================");
    },

    // 拷贝 NDEF 信息
    onClickNDEFContent() {
      const data = this.nfcInfo.payload;
      if (isEmpty(data)) return;

      wx.setClipboardData({ data });
    },

    // 关闭 NFC
    closeNFC() {
      if (this.NFCAdapter) {
        this.NFCAdapter.offDiscovered(this.discoverHandler);
        this.NFCAdapter.stopDiscovery();
        this.NFCAdapter = null;
      }
    },

    // 获取剪切板内容
    getClipboardData() {
      wx.getClipboardData({
        success: (res) => {
          const { data } = res;

          if (data && data != this.strContent) {
            wx.showModal({
              title: "识别到剪切板内容，是否粘贴？",
              content: data,
              confirmText: "粘贴",
              cancelText: "不了",
              confirmColor: "#22c068",
              cancelColor: "#999",
              showCancel: true,
              success: (result) => {
                if (result.confirm) {
                  this.strContent = data;
                }
              },
            });
          }
        },
      });
    },

    onInputStr(e) {
      this.strContent = e.detail.value;
    },
    /**
     * 批量加载
     */
    onTapLoad: throttle(function () {
      const strContent = this.strContent.trim();
      // 按 '逗号' 和 '回车' 进行分割
      // const data = strContent.split(/[\n,，]/g);
      const data = strContent.split(/[\n]/g);
      const list = [];
      // 移除空数据
      for (let i = 0; i < data.length; i++) {
        if (data[i] == "") {
          data.splice(i, 1);
          i--;
        } else {
          list.push({
            idx: i + 1,
            text: data[i],
            writeState: 0,
            verificationState: 0,
          });
        }
      }

      console.log("list", list);

      if (isEmpty(list)) {
        wx.showToast({
          title: "分割数据为空，请重试！",
          icon: "none",
        });
      } else {
        this.onRecordList({
          list,
        });
      }
    }),

    onRecordList({ list, key }) {
      console.log("key", key);
      if (!key) {
        key = `record_${generateUUID()}`;
        wx.setStorageSync(key, list);
      }

      uni.navigateTo({
        url: "/pages/NFCWriteList/NFCWriteList?key=" + key,
        success: () => {
          this.lastKey = key;
        },
      });
    },

    // 清除
    onClear() {
      this.strContent = "";
    },

    // 继续上次操作
    onLastOperate() {
      this.onRecordList({
        key: this.lastKey,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  padding: 20px;
  background-color: #ffffff;
}

.msg-box {
  min-height: 300rpx;
  border-radius: 30rpx;
  overflow: hidden;
  box-shadow: 0px 4px 16px 0px #edeef0;
  margin-bottom: 30rpx;
}

.msg-box .text {
  text-align: center;
  line-height: 40rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
}

.ndef-box {
  border-radius: 30rpx;
  overflow: hidden;
  min-height: 500rpx;
  padding-bottom: 10px;
  box-shadow: 0px 4px 16px 0px #edeef0;
}

.msg-box .title,
.ndef-box .title {
  font-weight: 700;
  text-align: center;
  line-height: 100rpx;
  border-bottom: 1px solid #f2f2f2;
}

.ndef-box .content {
  display: flex;
  padding: 10px;
  font-size: 28rpx;
  line-height: 36rpx;
}

.ndef-box .content .label {
  font-weight: 700;
  min-width: 90rpx;
}

.ndef-box .placeholder {
  line-height: 188rpx;
  text-align: center;
  color: #666;
  font-size: 28rpx;
}

.page_input {
  padding: 20px;
  background-color: #ffffff;
}

.load-textarea {
  box-shadow: 0px 4px 16px 0px #edeef0;
  width: 100%;
  padding: 20rpx;
  height: calc(100vh - 600rpx);
  font-size: 16px;
  box-sizing: border-box;
  border-radius: 12px;
}

.btn-load {
  width: 100%;
  line-height: 80rpx;
  text-align: center;
  font-size: 30rpx;
  border-radius: 20rpx;
  margin: 30rpx auto;
  color: #fff;
  background-color: #22c068;
}

.btn-clear {
  width: 100%;
  line-height: 80rpx;
  text-align: center;
  font-size: 30rpx;
  border-radius: 20rpx;
  margin: 30rpx auto;
  color: #22c068;
  box-shadow: 0px 4px 16px 0px #edeef0;
}
</style>
